﻿using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class ToolsWindow : EditorWindow
{
    [MenuItem("Tools/工具集")]
    static void ShowWindow()
    {
        GetWindow<ToolsWindow>("工具集").Show();
    }

    Vector2 pos;
    Dictionary<string, List<ToolButton>> pairs = new Dictionary<string, List<ToolButton>>();

    private void OnEnable()
    {
        foreach (Type type in this.GetType().Assembly.GetTypes())
        {
            object[] objects = type.GetCustomAttributes(typeof(ToolButtonAttribute), false);
            if (objects.Length == 0)
            {
                continue;
            }

            var attribute = (ToolButtonAttribute)objects[0];

            if (!pairs.ContainsKey(attribute.type))
            {
                pairs.Add(attribute.type, new List<ToolButton>());
            }
            var Instance = Activator.CreateInstance(type);
            pairs[attribute.type].Add(new ToolButton
            {
                title = attribute.title,
                buttonEvent = Instance as IToolsButtonEvent
            });
        }
    }

    private void OnGUI()
    {
        EditorGUILayout.BeginHorizontal();
        {
            pos = EditorGUILayout.BeginScrollView(pos);
            {
                foreach (var item in pairs)
                {
                    EditorGUILayout.BeginVertical("Box");
                    {
                        GUILayout.Label(item.Key);
                        foreach (var button in item.Value)
                        {
                            if (GUILayout.Button(button.title))
                            {
                                button.buttonEvent.Run();
                            }
                        }
                    }
                    EditorGUILayout.EndVertical();
                }
            }
            EditorGUILayout.EndScrollView();
        }
        EditorGUILayout.EndHorizontal();

    }

    void DrawList(string title, Action update)
    {
        EditorGUILayout.BeginVertical("Box");
        {
            var labelRect = EditorGUILayout.GetControlRect();
            EditorGUI.DrawRect(labelRect, Color.white);
            GUI.Label(labelRect, title);
            update();
        }
        EditorGUILayout.EndVertical();
    }

    struct ToolButton
    {
        public string title;
        public IToolsButtonEvent buttonEvent;
    }
}

//public class ReplaceScript : Editor
//{
//    [MenuItem("CONTEXT/MonoBehaviour/替换脚本")]
//    static void Run(MenuCommand command)
//    {
       
//    }
//}   